package com.sw.haruka.view

import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.sw.haruka.R
import com.sw.haruka.model.BaseActivity
import com.sw.haruka.model.DownloadObserver
import com.sw.haruka.model.FileRequestManager
import com.sw.haruka.model.entity.FileShareTask
import com.sw.haruka.module.share.monitor.MonitorAdapter
import com.sw.haruka.module.title.TitleBar
import com.sw.haruka.module.title.TitleMode
import com.sw.haruka.module.title.TransformerTitleFragment
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class DownloadMonitorActivity : BaseActivity(), DownloadObserver {
    private var mTaskRv: RecyclerView? = null
    private var mMonitorAdapter: MonitorAdapter? = null
    private var mEmptyView: TextView? = null
    private val service: ExecutorService = Executors.newSingleThreadExecutor()

    private var mTaskList: MutableList<FileShareTask?>? = null

    override fun layoutId(): Int {
        return R.layout.activity_download_monitor
    }

    override fun initView() {
        FileRequestManager.getInstance().addObserver(this)
        supportFragmentManager.beginTransaction()
            .add(R.id.title_ll, TitleBar.newInstance(getString(R.string.download_monitor_title)))
            .commit()
        mTaskRv = findViewById<RecyclerView>(R.id.recyclerView_downloadRanks)
        mTaskRv!!.setLayoutManager(LinearLayoutManager(this))
        mTaskList = ArrayList<FileShareTask?>()
        mMonitorAdapter = MonitorAdapter(mTaskList)
        mMonitorAdapter!!.setOnItemClickListener(OnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            if (view!!.getId() == R.id.imageButton_cancel) {
                service.execute(Runnable {
                    FileRequestManager.getInstance().cancelTask(position)
                })
                Toast.makeText(mContext, "已取消任务", Toast.LENGTH_SHORT).show()
            }
        })
        mTaskRv!!.setAdapter(mMonitorAdapter)
        mEmptyView = findViewById<TextView>(R.id.empty_tv)
    }

    override fun loadData(isRefresh: Boolean) {
    }

    override fun currentTaskList(taskList: MutableList<FileShareTask?>) {
        mTaskList!!.clear()
        mTaskList!!.addAll(taskList)
        runOnUiThread(Runnable {
            mMonitorAdapter!!.notifyDataSetChanged()
            mEmptyView!!.setVisibility(if (mTaskList!!.size == 0) View.VISIBLE else View.GONE)
        })
    }
}
